package torres.fileIO;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import torres.map.World;

public class Saver {

	public static void save(String fileName) {
		
		FileWriter fstream;
		ClassContainer  topClass = World.getInstance().save();
		try {
			fstream = new FileWriter(fileName);
			BufferedWriter bwriter = new BufferedWriter(fstream);
			bwriter.write(topClass.toString());
			bwriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void load(File saveFile) {
		
		String line;
		
		try {
			
			Scanner reader = new Scanner(saveFile);
			line = reader.nextLine();
			line = line.replace("<", "");
			line = line.replace(">", "");
			line = line.trim();
			ClassContainer classCont = new ClassContainer(line);
			while(true) {
				PropertyContainer property = load(reader);
				if(property==null)
					break;
				classCont.addProperty(property);
			}
			//System.out.println(classCont.toString());
			
			World world = World.getInstance();
			//System.out.println("hey");
			world.load(classCont);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private static PropertyContainer load(Scanner reader) {
			
		if(reader.hasNext()) {
			String line = reader.nextLine();
			int firstBracket;
			int secondBracket;
		//	boolean first=true;
		//	boolean end = false;
			PropertyContainer property;
			firstBracket = line.indexOf("<");
			secondBracket = line.indexOf(">");
			String name = line.substring(firstBracket+1, secondBracket);
			ClassContainer classCont;
			classCont = new ClassContainer(name);
			if(line.contains("<value>")) {
				firstBracket = line.indexOf("<");
				secondBracket = line.indexOf(">");
				name = line.substring(firstBracket+1, secondBracket);
				line = line.substring(secondBracket+1);
				line = line.replace("<value>", " ");
				int thirdBracket = line.indexOf("</");
				line = line.substring(0, thirdBracket);
				String value = line;
				value = value.trim();
				property = new BasicContainer(name, value);
				return property;
			}
			else if(line.contains("/")) {
				property=null;
				return property;
			}
			else {
				while(true) {
					property = load(reader);
					if(property==null) {
						return classCont;
					}
					classCont.addProperty(property);
				}


			}
		}
		return null;
	}
	
	
}
